package com.empire.module.member.service.internetarticle;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.empire.module.member.controller.admin.internetarticle.vo.*;
import com.empire.module.member.dal.dataobject.internetarticle.InternetArticleDO;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.common.util.object.BeanUtils;

import com.empire.module.member.dal.mysql.internetarticle.InternetArticleMapper;

import javax.annotation.Resource;

import static com.empire.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.empire.module.member.enums.ErrorCodeConstants.*;

/**
 * 互联网文章 Service 实现类
 *
 * @author 主席大人
 */
@Service
@Validated
public class InternetArticleServiceImpl implements InternetArticleService {

    @Resource
    private InternetArticleMapper internetArticleMapper;

    @Override
    public Long createInternetArticle(InternetArticleSaveReqVO createReqVO) {
        // 插入
        InternetArticleDO internetArticle = BeanUtils.toBean(createReqVO, InternetArticleDO.class);
        internetArticleMapper.insert(internetArticle);
        // 返回
        return internetArticle.getId();
    }

    @Override
    public void updateInternetArticle(InternetArticleSaveReqVO updateReqVO) {
        // 校验存在
        validateInternetArticleExists(updateReqVO.getId());
        // 更新
        InternetArticleDO updateObj = BeanUtils.toBean(updateReqVO, InternetArticleDO.class);
        internetArticleMapper.updateById(updateObj);
    }

    @Override
    public void deleteInternetArticle(Long id) {
        // 校验存在
        validateInternetArticleExists(id);
        // 删除
        internetArticleMapper.deleteById(id);
    }

    private void validateInternetArticleExists(Long id) {
        if (internetArticleMapper.selectById(id) == null) {
            throw exception(INTERNET_ARTICLE_NOT_EXISTS);
        }
    }

    @Override
    public InternetArticleDO getInternetArticle(Long id) {
        return internetArticleMapper.selectById(id);
    }

    @Override
    public PageResult<InternetArticleDO> getInternetArticlePage(InternetArticlePageReqVO pageReqVO) {
        return internetArticleMapper.selectPage(pageReqVO);
    }

}